<template>
  <div id="rwMap" class="mapContainer"></div>
</template>

<script setup lang="ts">
import AMapLoader from '@amap/amap-jsapi-loader'
import { propTypes } from '@/utils/propTypes'

const emits = defineEmits(['locateChange'])
const state = reactive({
  lonLat : '',
  config: { properties: { securityJsCode: undefined, apiKey: '' }},
  loading: false,
  //纬度、经度
  locate: {},
  //地图对象
  map: null as any,
  //标记对象
  mapMarker:null as any,
})
const props = defineProps({
  config: propTypes.object.def({}),
  clickMap: propTypes.bool.def(false),
  isWrite: propTypes.bool.def(false),
  locate: propTypes.object.def(undefined),
})

const loadMap = () => {
  (window as any)._AMapSecurityConfig = {
    securityJsCode: state.config.properties.securityJsCode,
  }
  state.locate = props.locate
  AMapLoader.load({
    key: state.config.properties.apiKey, // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [
      //逆解析插件
      'AMap.Geocoder',
      'AMap.AutoComplete',
    ],
  }).then(() => {
    initMap()
    if(props.clickMap){
        state.map.on('click', (e) =>{
          state.lonLat=e.lnglat.lng + ',' + e.lnglat.lat
          regeoCode(state.lonLat)
        })
    }
  })
}

const initMap=()=> {
  let mapId=props.isWrite ? 'rwMap' : 'rMap'
  state.map = new (window as any).AMap.Map(mapId, {
    resizeEnable: true,
    zoom: 11, //地图显示的缩放级别
    keyboardEnable: false,
  })

  if(props.locate.latitude && props.locate.longitude) {
    setMarker([props.locate.longitude, props.locate.latitude])
  }
}

//添加标记点
const setMarker=(lnglat)=> {
  if (lnglat) {
    if (state.mapMarker !== null) {
      // 如果点标记已存在则先移除原点
      state.map.remove(state.mapMarker)
      state.lonLat = ''
    }
    state.mapMarker = new (window as any).AMap.Marker({
      // 定义点标记对象
      position: new (window as any).AMap.LngLat(lnglat[0], lnglat[1]),
    })
    state.map.add(state.mapMarker) // 添加点标记在地图上
    state.map.setCenter(lnglat)
    state.map.setZoom(12)
    state.mapMarker.setPosition(lnglat)
  }
}

//经纬度转化为地址、添加标记点
const regeoCode=(lonLat)=>{
  if (lonLat) {
    let lnglat = lonLat.split(',')
    state.locate = { latitude: lnglat[0], longitude: lnglat[1]}
    emits('locateChange', state.locate)
    setMarker(lnglat)
  }
}


watch(() => props.config, (v:any) => {
  state.config = v
  loadMap()
}, { immediate: true })
</script>

<style scoped>
.mapContainer {
  width: 100%;
  height: 240px;
}
</style>
